package com.momoauth.api_client.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.momoauth.api_client.entity.Department;
import com.momoauth.api_client.mapper.DepartmentMapper;
import com.momoauth.api_client.mapper.UserMapper;
import com.momoauth.common.core.result.ResponseResurt;
import com.momoauth.common.security.annotation.RequiresRoles;
import com.momoauth.common.security.enumeration.Logical;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/department")
@Api(tags = "部门")
@RequiresRoles(value = {"超级管理员","普通管理员"}, logical = Logical.OR)
public class DepartmentController {

    @Resource
    DepartmentMapper departmentMapper;

    @Resource
    UserMapper userMapper;

    /**
     * 部门列表
     * @param department
     * @return
     */
    @ApiOperation(value = "部门列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页数", required = true)
    })
    @RequestMapping(value = "/getDepartmentList", method = RequestMethod.GET)
    public ResponseResurt getDepartmentList(Department department) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isDelete", 0);
        queryWrapper.orderByDesc("deptId"); //按主键倒序排序
        queryWrapper.like(!StringUtils.isEmpty(department.getKeywords()),"deptName", department.getKeywords());
        queryWrapper.eq(department.getStatus() != 0,"status", department.getStatus());
        Page<Department> page = new Page<>(department.getCurrentPage(), department.getPageSize());
        page.setRecords(departmentMapper.getDepartmentList(page, queryWrapper));
        return ResponseResurt.success().data(page);
    }

    /**
     * 可用的部门列表
     * @param department
     * @return
     */
    @ApiOperation(value = "可用的部门列表")
    @ApiImplicitParam(name = "deptId", value = "部门ID（主键）", required = true)
    @RequestMapping(value = "/getAvailableDepartmentList", method = RequestMethod.GET)
    public ResponseResurt getAvailableDepartmentList(Department department) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("isDelete", 0);
        // 传入主键ID排除自身
        if (department.getDeptId() > 0) {
            queryWrapper.ne("deptId", department.getDeptId());
            queryWrapper.ne("parentId", department.getDeptId());
        }
        queryWrapper.select("deptId", "deptName");
        List<Department> departmentList = departmentMapper.selectList(queryWrapper);
        return ResponseResurt.success().data(departmentList);
    }

    /**
     * 创建部门
     * @param department
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "创建部门")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptName", value = "部门名称", required = true),
            @ApiImplicitParam(name = "description", value = "描述", required = false),
            @ApiImplicitParam(name = "parentId", value = "父部门ID", required = true),
            @ApiImplicitParam(name = "status", value = "状态", required = true)
    })
    @RequestMapping(value = "/createDepartment", method = RequestMethod.POST)
    public ResponseResurt createDepartment(
            @Validated Department department,
            BindingResult bindingResult
    ) {
        // 非法参数验证
        if(bindingResult.hasErrors()){
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResponseResurt.error().msg(errorMsg);
        }
        // 执行新增操作
        int isInsert = departmentMapper.insert(department);
        if (isInsert > 0) {
            return ResponseResurt.success().msg("恭喜您，创建成功。");
        }
        return ResponseResurt.error().msg("很抱歉，创建失败。");
    }

    /**
     * 修改部门
     * @param department
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateDepartment", method = RequestMethod.GET)
    @ApiOperation(value = "修改部门")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID（主键）", required = true),
            @ApiImplicitParam(name = "deptName", value = "部门名称", required = true),
            @ApiImplicitParam(name = "description", value = "描述", required = false),
            @ApiImplicitParam(name = "parentId", value = "父部门ID", required = true),
            @ApiImplicitParam(name = "status", value = "状态", required = true)
    })
    public ResponseResurt updateDepartment(
            @Validated Department department,
            BindingResult bindingResult
    ) {
        // 非法参数验证
        if(bindingResult.hasErrors()){
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResponseResurt.error().msg(errorMsg);
        }
        // 查询当前版本号
        long version = departmentMapper.selectById(department.getDeptId()).getVersion();
        department.setVersion(version);
        // 执行更新操作
        int isUpdate = departmentMapper.updateById(department);
        if (isUpdate > 0) {
            return ResponseResurt.success().msg("恭喜您，修改成功。");
        }
        return ResponseResurt.error().msg("很抱歉，修改失败！");
    }

    /**
     * 删除部门
     * @param department
     * @return
     */
    @ApiOperation(value = "删除部门")
    @ApiImplicitParam(name = "deptId", value = "部门ID（主键）", required = true)
    @RequestMapping(value = "/deleteDepartment", method = RequestMethod.GET)
    public ResponseResurt deleteDepartment(Department department) {
        // 存在子级部门时不可直接删除
        Integer isExist = departmentMapper.existChildrenDeptByParentId(department.getDeptId());
        if (isExist != null) {
            return ResponseResurt.error().msg("该部门存在子级部门，无法删除。");
        }
        // 存在用户使用时不可删除
        isExist = userMapper.existUserUseDepartmentById(department.getDeptId());
        if (isExist != null) {
            return ResponseResurt.error().msg("该部门存在用户使用，无法删除。");
        }
        // 执行更新操作（逻辑删除）
        int isUpdate = departmentMapper.deleteDepartmentById(department.getDeptId());
        if (isUpdate > 0) {
            return ResponseResurt.success().msg("恭喜您，删除成功。");
        }
        return ResponseResurt.error().msg("很抱歉，删除失败！");
    }

    /**
     * 部门详情
     * @param department
     * @return
     */
    @ApiOperation(value = "部门详情")
    @ApiImplicitParam(name = "deptId", value = "部门ID（主键）", required = true)
    @RequestMapping(value = "/getDepartmentById", method = RequestMethod.GET)
    public ResponseResurt getDepartmentById(Department department) {
        department = departmentMapper.selectById(department.getDeptId());
        return ResponseResurt.success().data(department);
    }
}
